<template>
	<view class="page_full">
		<view class="page_top">
			<view class="page_top_conetnt">
				<image src="@/static/logo/back_icon.png" mode="" class="back_logo"
				@click="back"></image>
				<text>{{ pageTitle }}</text>
				
				<text class="del_text" @click="deleteFn" v-if="pageTitle==='工单查看'&&optionsData.status!='5'">删除</text>
			</view>
		</view>
		<scroll-view scroll-y="true" class="page_scroll_box">
			<view class="page_scroll_content">
				<view class="form_cell">
					<view class="form_title">
						<text>工单标题:</text>
					</view>
					<view class="form_content">
						<u-input v-model="form.title" placeholder="请输入工单标题" border="surround"
						:disabled="pageTitle!=='创建工单'"></u-input>
					</view>
				</view>
				<view class="form_cell">
					<view class="form_title">
						<text>工单描述:</text>
					</view>
					<view class="form_content">
						<u-textarea v-model="form.detail" :count="true" placeholder="请输入工单的详细描述" 
						:disabled="pageTitle!=='创建工单'"></u-textarea>
					</view>
				</view>
				<view class="form_cell">
					<view class="form_title">
						<text>图片详情:</text>
					</view>

					<view class="add_img_box" v-if="pageTitle==='创建工单'">
						<u-upload
							:fileList="imgList"
							@afterRead="afterRead"
							@delete="deletePic"
							name="file"
							multiple
							:maxCount="3"
							width="100"
							height="100"
							uploadText="上传文件"
						></u-upload>
					</view>
					
					<view class="form_content img_list" v-else>
						<view class="form_img_box" v-for="(item, index) in imgList" :key="index">
							<image :src="item.url" mode="aspectFill" @click="perviewImg(item)"></image>
						</view>
					</view>
				</view>
				
				<view class="submit_btn" v-if="pageTitle==='创建工单'">
					<u-button type="primary" text="提 交" @click="submit"></u-button>
				</view>
				
				<view class="submit_btn" v-if="pageTitle==='接受工单'">
					<u-button type="primary" text="接 收" @click="receiveFn"></u-button>
				</view>
			</view>
		</scroll-view>
		
		<u-toast ref="uToastRef"></u-toast>
		
		<u-modal :show="delModel.show" title="提示" content='是否确认删除本工单!'
		:showCancelButton="true" @cancel="delModel.show=false" @confirm="confirmDel"></u-modal>
	</view>
</template>

<script setup>
	import { onLoad } from "@dcloudio/uni-app"
	import { ref, reactive, computed } from 'vue'
	import { baseUrl } from '@/utils/baseConfig.js'
	import { addWorkOrderAPI, getOrderInfoAPI, deleteOrderAPI } from '@/api/initiate.js'
	import { receiveOrderAPI } from '@/api/receive.js' 
	
	const uToastRef = ref(null)
	
	let optionsData = reactive({
		id: undefined,
		type: undefined,
		status: undefined
	})
	
	let delModel = reactive({
		show: false,
		content: "是否确定删除本工单！"
	})
	
	const pageTitle = computed(()=>{
		if(optionsData.type == 'initiate' && optionsData.id) {
			return "工单查看"
		} else if(optionsData.type == "receive" && optionsData.id) {
			return "接受工单"
		} else {
			return "创建工单"
		}
	})
	
	const initFrom = {
		title: "",
		detail: "",
		filePath: []
	}
	
	let imgList = ref([])
	
	let form = ref({...initFrom})
	
	
	function back() {
		uni.navigateBack(-1)
	}
	
	// 删除图片
	function deletePic(event) {
		imgList.value.splice(event.index, 1)
	}
	
	// 新增图片
	async function afterRead(event) {
		// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
		let lists = [].concat(event.file)
		let fileListLen = imgList.value.length
		lists.map((item) => {
			imgList.value.push({
				...item,
				status: 'uploading',
				message: '上传中'
			})
		})
		for (let i = 0; i < lists.length; i++) {
			const result = await uploadFilePromise(lists[i].url)
			imgList.value.splice(fileListLen, 1, { url: result })
			fileListLen++
		}
	}
	
	function uploadFilePromise(url) {
		return new Promise((resolve, reject) => {
			let a = uni.uploadFile({
				url: `${baseUrl}/workorder/work/upload`,
				header:{
					"Authorization": "Bearer " + uni.getStorageSync('token')|| "",
					"clientId": uni.getStorageSync('client_id')||"",
				},
				filePath: url,
				name: 'file',
				formData: {
					user: 'test'
				},
				success: (res) => {
					let data = JSON.parse(res.data)
					resolve(data.data[0])
				}
			});
		})
	}
	
	async function submit() {
		
		console.log(imgList.value)
		
		if(!form.value.detail||!form.value.title) {
			return uToastRef.value.show({
				type: 'warning',
				message: "请填写标题和工单描述"
			})
		}
		
		form.value.filePath = imgList.value.map(ele=>{ return ele.url })
		const res = await addWorkOrderAPI(form.value)
		console.log("提交的结果位", res)
		if(res.code === 200) {
			uToastRef.value.show({
				type: 'success',
				message: "提交成功"
			})
			setTimeout(()=>{
				uni.navigateBack(-1)
			})
		}
	}
	
	/** 接受工单 */
	async function receiveFn() {
		const res = await receiveOrderAPI({
			type: 2,
			id: optionsData.id
		})
		if(res.code == 200) {
			uToastRef.value.show({
				type: 'success',
				message: '接收成功'
			})
			uni.setStorageSync("reget", true)
			setTimeout(()=>{
				uni.navigateBack(-1)
			},1000)
		}
	}
	
	async function getOrderInfoFn(id) {
		const res = await getOrderInfoAPI(id)
		if(res.code == 200) {
			form.value = res.data
			imgList.value = form.value.userPath.map(ele=>{ return { url: ele } })
		}
	}
	
	function deleteFn() {
		delModel.show = true
	}
	
	async function confirmDel() {
		const res = await deleteOrderAPI(optionsData.id)
		if(res.code == 200) {
			uToastRef.value.show({
				type: 'success',
				message: '删除成功'
			})
			uni.setStorageSync("reget", true)
			delModel.show = false
			setTimeout(()=>{
				uni.navigateBack(-1)
			},1000)
		}
	}
	
	function perviewImg(item) {
		uni.previewImage({
			loop: true,
			urls: imgList.value.map(ele=>{ return ele.url }),
			current:item.url
		})
	}
	
	onLoad((options)=>{
		optionsData.id = options.id
		optionsData.status = options.status
		optionsData.type = options.type
		if(options.id) {
			getOrderInfoFn(options.id)
		}
	})
</script>

<style scoped lang="scss">
	.page_full {
		height: 100vh;
	}
	.page_top {
		width: 100%;
		height: calc(var(--status-bar-height) + 88rpx);
		padding-top: var(--status-bar-height);
		background-color: #f8f8f8;
		position: relative;
		
		.page_top_conetnt {
			display: flex;
			align-items: center;
			justify-content: center;
			width: 100%;
			height: 100%;
			position: relative;
		}
		.back_logo {
			--back-img-size: 40rpx;
			width: var(--back-img-size);
			height: var(--back-img-size);
			position: absolute;
			top: 50%;
			left: 30rpx;
			transform: translateY(-50%);
		}
		.del_text {
			position: absolute;
			right: 30rpx;
			color: $uni-color-error;
			font-size: 24rpx;
			top: 50%;
			transform: translateY(-50%);
		}
	}
	.page_scroll_box {
		width: 100%;
		height: calc(100% - var(--status-bar-height) - 88rpx);
		.page_scroll_content {
			min-height: 100%;
			padding: 30rpx;
			background-color: #fff;
		}
	}
	.form_cell {
		width: 100%;
		padding-bottom: 12rpx;
		border-bottom: 1rpx solid $uni-color-border;
		.form_title {
			padding: 16rpx;
			font-size: 28rpx;
		}
		.form_content {
			
		}
		.add_img_box {
			margin-top: 12rpx;
			// background-color: #fff;
		}
		.img_list {
			display: flex;
			padding-left: 1em;
			margin-top: 12rpx;
		}
		.form_img_box {
			width: 30%;
			aspect-ratio: 1/1;
			margin-left: 5%;
			overflow: hidden;
			image{
				width: 100%;
				height: 100%;
			}
		}
		.form_img_box:first-child {
			margin-left: 0;
		}

	}
	
	.submit_btn {
		margin-top: 50rpx;
	}
	
	
</style>
